<template>
  <el-tree-select v-model="selectValue" :key="selectValue" 
    :data="regionOptions" :props="propsData" 
    :value-key="type=='id'?'id':'adcode'" check-strictly placeholder="选择行政区划" 
    @node-click="changeselectValue" clearable @change="change"/>
</template>

<script setup>
import useUserStore from "@/store/modules/user";

const userStore = useUserStore();
const props = defineProps({
  regionId: {
    type: Number,
  },
  regionCode:{
    type: String,
  },
  regionLevel:{
    type: Number,
  },
  //传参类型code或者id
  type:{
    type: String,
    default:'id'
  },
});
const emit = defineEmits(["update:regionId","update:regionCode","update:regionLevel"]);

let selectValue = ref(null);
const regionOptions = computed(() => userStore.regionOptions);
const propsData = computed(() => {
  if(props.type=='id') {
    return { value: 'id', label: 'name', children: 'children' };
  }else if(props.type=='code') {
    return { value: 'adcode', label: 'name', children: 'children' };
  }
});

watch(() => props.regionId,
  async (val) => {
    selectValue.value = val;
  },
  { deep: true, immediate: true }
);
watch(() => props.regionCode,
  async (val) => {
    selectValue.value = val;
  },
  { deep: true, immediate: true }
);

function changeselectValue(e) {
  emit("update:regionId", e.id);
  emit("update:regionCode", e.adcode);
  emit("update:regionLevel", e.level);
}
function change(e) {
  if(!e) {
    emit("update:regionId", null);
    emit("update:regionCode", null);
    emit("update:regionLevel", null);
  }
}
</script>

<style lang="scss" scoped>
:deep(.el-select) {
  width: 100%;
}
</style>